<?php

namespace app\admin\server;

use app\admin\model\wxwork\LocalMediaModel;
use app\admin\model\wxwork\WelcomeDemoModel;
use app\admin\model\wxwork\WelcomeDemoUserListModel;
use app\common\logic\BaseLogic;
use think\Exception;

class WelcomeServer
{
    //添加
    public static function add(array $params)
    {
        /**
         * {
         *      'wd_in_use':1,             //是否启用 1 是 2否
         *      'wd_content':'测试',     //欢迎语内容
         *      'user_list':'ZhouWenkang', //配置的成员workerid,逗号分隔的字符串
         *      //附件数组
         *      'file_arr': [
         *      {
         *          'type'=>1,      //图片
         *          'value1'=>113,  //素材id
         *      },
         *      {
         *           'type'=>2,      //网页链接
         *           'value1'=>111,  //封面图素材id
         *           'value2'=>111,  //网页链接标题
         *           'value3'=>111,  //网页链接描述
         *           'value4'=>17,   //网页链接地址
         *      },
         *      {
         *          'type'=>3,      //小程序
         *          'value1'=>17,   //小程序封面图素材id
         *          'value2'=>111,  //小程序标题
         *          'value3'=>'wx14654497ad6dad10', //小程序appid
         *          'value4'=>'/pages/index/index' //小程序页面路径
         *      },
         *      {
         *          'type'=>4,      //视频
         *          'value1'=>32    //素材id
         *      },
         *      {
         *          'type'=>5,      //文件
         *          'value1'=>83    //素材id
         *      }
         *      ]
         * }
         */
        $file_arr = $params['file_arr'] ?? [];
        if(empty(my_trim($params['wd_content'])) && empty($file_arr)) {
            throw new Exception('文字内容与附件内容不能同时为空');
            return false;
        }
        if(my_str_length($params['wd_content']) > 4000) {
            throw new Exception('文字内容字数超限');
            return false;
        }
        $data['wd_cate'] = 1;
        $data['wd_content'] = $params['wd_content'];
        $time = time();
        if(!empty($file_arr)) {
            foreach($file_arr as $i => $item) {
                $file_arr[$i] = json_decode($file_arr[$i], true);
                switch($file_arr[$i]['type']) {
                    //图片
                    case '1':
                        //视频
                    case '4':
                        //文件
                    case '5':
                        if($file_arr[$i]['value1'] == '') {
                            throw new Exception('附件内容请填写完整');
                            return false;
                        }
                        $file_arr[$i]['local_path'] = LocalMediaModel::where('id', '=', $file_arr[$i]['value1'])->value('media_path');
                        break;
                    //链接
                    case '2':
                        if($file_arr[$i]['value1'] == '' || $file_arr[$i]['value2'] == '' || my_trim($file_arr[$i]['value3']) == '' || $file_arr[$i]['value4'] == '') {
                            throw new Exception('附件内容请填写完整');
                            return false;
                        }
                        if(my_str_length($file_arr[$i]['value2']) > 128) {
                            throw new Exception('链接标题字数超限');
                            return false;
                        }
                        if(my_str_length($file_arr[$i]['value3']) > 512) {
                            throw new Exception('链接描述字数超限');
                            return false;
                        }
                        if(my_str_length($file_arr[$i]['value4']) > 2048) {
                            throw new Exception('链接地址字数超限');
                            return false;
                        }
                        $file_arr[$i]['local_path'] = LocalMediaModel::where('id', '=', $file_arr[$i]['value1'])->value('media_path');
                        break;
                    //小程序
                    case '3':
                        if($file_arr[$i]['value1'] == '' || $file_arr[$i]['value2'] == '' || my_trim($file_arr[$i]['value3']) == '' || $file_arr[$i]['value4'] == '') {
                            throw new Exception('附件内容请填写完整');
                            return false;
                        }
                        if(my_str_length($file_arr[$i]['value2']) > 64) {
                            throw new Exception('小程序标题字数超限');
                            return false;
                        }
                        $file_arr[$i]['local_path'] = LocalMediaModel::where('id', '=', $file_arr[$i]['value1'])->value('media_path');
                        break;
                }
            }
        }
        $data['wd_file_arr'] = serialize($file_arr);
        $data['wd_in_use'] = $params['wd_in_use'];
        $data['update_time'] = $time;
        $data['admin_id'] = $params['admin_id'];
        $data['update_people'] = $params['admin_username'];
        var_dump($data);
        exit();
        try {
            if(!empty($params['user_list'])) {
                $user_list = explode(',', $params['user_list']);
                $arr1 = WelcomeDemoUserListModel::alias('a')
                    ->leftJoin('wxwork_welcome_demo b', 'b.id=a.demo_id')
                    ->leftJoin('wxwork_company_worker c', 'c.worker_id=a.worker_id')
                    ->where('b.delete_time', '=', 0)
                    ->field('c.worker_id,c.worker_name')
                    ->select()
                    ->toArray();
                $arr2 = [];
                foreach($arr1 as $i => $item) {
                    $arr2[$arr1[$i]['worker_id']] = $arr1[$i];
                }
                $arr3 = array_column($arr1, 'worker_id');
                $arr4 = array_values(array_intersect($user_list, $arr3));
                $arr5 = [];
                if(!empty($arr4)) {
                    foreach($arr4 as $i => $item) {
                        if(isset($arr2[$arr4[$i]])) {
                            array_push($arr5, $arr2[$arr4[$i]]['worker_name']);
                        }
                    }
                    throw new Exception('以下成员已配置过欢迎语，请重新选择成员：' . implode('，', $arr5));
                    return false;
                }
            } else {
                $user_list = [];
            }
            $WelcomeDemoModel = new WelcomeDemoModel;
            $WelcomeDemoModel->save($data);
            $demo_id = $WelcomeDemoModel->id;
            if(!empty($user_list)) {
                $data2 = [];
                foreach($user_list as $i => $item) {
                    $data2[] = [
                        'demo_id'   => $demo_id,
                        'worker_id' => $user_list[$i]
                    ];
                }
                (new WelcomeDemoUserListModel())->saveAll($data2);
            }
//            (new BaseLogic)->saveWxworkOperationLog('la_wxwork_welcome_demo添加欢迎语【id:' . $demo_id . '】');
            return true;
        } catch(Exception $e) {
            throw new Exception($e->getMessage());
            return false;
        }
    }

    //修改
    public static function edit(array $params)
    {
        /**
         * {
         * 'id': 0,
         * 'wd_in_use':1,             //是否启用 1 是 2否
         * 'wd_content':'测试',     //欢迎语内容
         * 'user_list':'ZhouWenkang', //配置的成员workerid,逗号分隔的字符串
         * //附件数组
         * 'file_arr': [
         * {
         * 'type'=>1,      //图片
         * 'value1'=>113,  //素材id
         * },
         * {
         * 'type'=>2,      //网页链接
         * 'value1'=>111,  //封面图素材id
         * 'value2'=>111,  //网页链接标题
         * 'value3'=>111,  //网页链接描述
         * 'value4'=>17,   //网页链接地址
         * },
         * {
         * 'type'=>3,      //小程序
         * 'value1'=>17,   //小程序封面图素材id
         * 'value2'=>111,  //小程序标题
         * 'value3'=>'wx14654497ad6dad10', //小程序appid
         * 'value4'=>'/pages/index/index' //小程序页面路径
         * },
         * {
         * 'type'=>4,      //视频
         * 'value1'=>32    //素材id
         * },
         * {
         * 'type'=>5,      //文件
         * 'value1'=>83    //素材id
         * }
         * ]
         * }
         */
        $file_arr = $params['file_arr'];
        if(empty(my_trim($params['wd_content'])) && empty($file_arr)) {
            throw new Exception('文字内容与附件内容不能同时为空');
            return false;
        }
        if(my_str_length($params['wd_content']) > 4000) {
            throw new Exception('文字内容字数超限');
            return false;
        }
        $data['wd_content'] = $params['wd_content'];
        $time = time();
        if(!empty($file_arr)) {
            for($i = 0; $i < count($file_arr); $i++) {
                $file_arr[$i] = json_decode($file_arr[$i], true);
                switch($file_arr[$i]['type']) {
                    //图片
                    case '1':
                        //视频
                    case '4':
                        //文件
                    case '5':
                        if($file_arr[$i]['value1'] == '') {
                            throw new Exception('附件内容请填写完整');
                            return false;
                        }
                        $file_arr[$i]['local_path'] = LocalMediaModel::where('id', '=', $file_arr[$i]['value1'])->value('media_path');
                        break;
                    //链接
                    case '2':
                        if($file_arr[$i]['value1'] == '' || $file_arr[$i]['value2'] == '' || myTrim($file_arr[$i]['value3']) == '' || $file_arr[$i]['value4'] == '') {
                            throw new Exception('附件内容请填写完整');
                            return false;
                        }
                        if(my_str_length($file_arr[$i]['value2']) > 128) {
                            throw new Exception('链接标题字数超限');
                            return false;
                        }
                        if(my_str_length($file_arr[$i]['value3']) > 512) {
                            throw new Exception('链接描述字数超限');
                            return false;
                        }
                        if(my_str_length($file_arr[$i]['value4']) > 2048) {
                            throw new Exception('链接地址字数超限');
                            return false;
                        }
                        $file_arr[$i]['local_path'] = LocalMediaModel::where('id', '=', $file_arr[$i]['value1'])->value('media_path');
                        break;
                    //小程序
                    case '3':
                        if($file_arr[$i]['value1'] == '' || $file_arr[$i]['value2'] == '' || myTrim($file_arr[$i]['value3']) == '' || $file_arr[$i]['value4'] == '') {
                            throw new Exception('附件内容请填写完整');
                            return false;
                        }
                        if(my_str_length($file_arr[$i]['value2']) > 64) {
                            throw new Exception('小程序标题字数超限');
                            return false;
                        }
                        $file_arr[$i]['local_path'] = LocalMediaModel::where('id', '=', $file_arr[$i]['value1'])->value('media_path');
                        break;
                }
            }
            $data['wd_file_arr'] = serialize($file_arr);
        }
        $data['wd_in_use'] = $params['wd_in_use'];
        $data['update_time'] = $time;
        $data['update_people'] = $params['adminInfo']['name'];
        try {
            if(!empty($params['user_list'])) {
                $user_list = explode(',', $params['user_list']);
                $arr1 = WelcomeDemoUserListModel::alias('a')
                    ->leftJoin('wxwork_welcome_demo b', 'b.id=a.demo_id')
                    ->leftJoin('wxwork_company_worker c', 'c.worker_id=a.worker_id')
                    ->where('b.delete_time', '=', 0)
                    ->field('c.worker_id,c.worker_name')
                    ->select()
                    ->toArray();
                $arr2 = [];
                for($i = 0; $i < count($arr1); $i++) {
                    $arr2[$arr1[$i]['worker_id']] = $arr1[$i];
                }
                $arr3 = array_column($arr1, 'worker_id');
                $arr4 = array_values(array_intersect($user_list, $arr3));
                $arr5 = [];
                if(!empty($arr4)) {
                    for($i = 0; $i < count($arr4); $i++) {
                        if(isset($arr2[$arr4[$i]])) {
                            array_push($arr5, $arr2[$arr4[$i]]['worker_name']);
                        }
                    }
                    throw new Exception('以下成员已配置过欢迎语，请重新选择成员：' . implode('，', $arr5));
                    return false;
                }
            } else {
                $user_list = explode(',', $params['user_list']);
            }
            (new WelcomeDemoModel())->where('id', '=', $params['id'])->save($data);
            if(!empty($user_list)) {
                $old_data = WelcomeDemoUserListModel::where('demo_id', '=', $params['id'])
                    ->column('worker_id');
                $del = array_values(array_diff($old_data, $user_list));
                $ins = array_values(array_diff($user_list, $old_data));
                $data2 = [];
                for($i = 0; $i < count($ins); $i++) {
                    $data2[] = [
                        'demo_id'   => $params['id'],
                        'worker_id' => $ins[$i]
                    ];
                }
                WelcomeDemoUserListModel::where('demo_id', '=', $params['id'])
                    ->where('worker_id', 'in', $del)
                    ->delete();
                (new WelcomeDemoUserListModel())->saveAll($data2);
            }
            return true;
        } catch(Exception $e) {
            throw new Exception($e->getMessage());
            return false;
        }
    }

    //删除
    public static function del(array $params)
    {
        $id = $params['id'];
        $time = time();
        $people = $params['adminInfo']['name'];
        if(is_array($id)) {
            $result = WelcomeDemoModel::where('id', 'in', $id)
                ->update([
                    'delete_time'   => $time,
                    'delete_people' => $people
                ]);
        } else {
            $result = WelcomeDemoModel::where('id', '=', $id)
                ->update([
                    'delete_time'   => $time,
                    'delete_people' => $people
                ]);
        }
        if($result !== false) {
            return true;
        } else {
            throw new Exception('删除失败');
            return false;
        }
    }
}